<?php

namespace plugin\coleopenapi\app\admin\controller;

use app\common\controller\BaseAdminController;
use Carbon\Carbon;
use core\utils\Time;
use plugin\coleopenapi\app\admin\validate\AppSignValidate;
use plugin\coleopenapi\app\logic\AppSignLogic;

class AppController extends BaseAdminController
{
    protected function init()
    {
        parent::init();
        $this->logic = new AppSignLogic();
        $this->validate = new AppSignValidate();
    }

    protected function searchWhere()
    {
        $where = [];
        $this->form['keyword'] && $where[] = ['app_name|app_key', 'like', "%{$this->form['keyword']}%"];
//        $this->form['app_key'] && $where[] = ['app_key', 'like', "%{$this->form['app_key']}%"];
        !is_null($this->form['status']) && $this->form['status'] != "" && $where[] = ['status', '=', $this->form['status']];
        return $where;
    }

    public function beforeAddOrEdit($type, &$data)
    {
        if ($type == self::ADD) {
            $data['expired_at'] = Carbon::now()->addYears(3)->toDateTimeString();
            $data['created_at'] = Time::now();
            $data['updated_at'] = Time::now();
        } else {
            $data['updated_at'] = Time::now();
            $this->logic->removeCache();
        }

    }


    public function remove()
    {
        $ids = request()->input('ids', [request()->input($this->idKey)]);
        if (!empty($ids)) {
            $this->logic->where(['id', 'in', $ids])->delete();
            $this->logic->removeCache();
            return $this->success();
        } else {
            return $this->error('参数错误，请检查');
        }
    }

    public function changeStatus()
    {
        $data = parent::changeStatus();
        $this->logic->removeCache();
        return $data;
    }

}
